# -*- encoding=UTF-8 -*-
import datetime
import json
import os
import threading
import time
from time import sleep
import requests
import serial
import uiautomator2 as u2
import datetime
from PIL.Image import Image

from Android.Doorbell_monitor import ResizeImage


class netcfg:

    def __init__(self, devices_name, packageName, com):
        self.packageName = packageName
        self.d = u2.connect_usb(devices_name)
        self.d.unlock()
        self.d.press("home")

        self.com = com
        self.read_serial = read_serial(com)

        self.pic = os.path.dirname(os.path.abspath(__file__)) + "/fail_pic/"
        self.result = os.path.dirname(os.path.abspath(__file__)) + "/report/"
        self.log = os.path.dirname(os.path.abspath(__file__)) + "/serial/"

        self.result_path = self.result + time.strftime("netcfg_%Y_%m_%d_%H_%M_%S", time.localtime()) + '.log'
        self.log_path = self.log + time.strftime("serial_%Y_%m_%d_%H_%M_%S", time.localtime()) + '.log'

        self.read_serial.set_log_path(self.log_path)
        self.read_serial.start()

        if not os.path.exists(self.result):
            os.makedirs(self.result)

        if not os.path.exists(self.log):
            os.makedirs(self.log)

        if not os.path.exists(self.pic):
            os.makedirs(self.pic)

        self.fail_time = 0

    def set_up(self):

        self.d.app_stop(self.packageName)
        sleep(1)
        self.d.app_start(self.packageName)

        gotimes = 0
        while True:
            if self.d(text="Home").exists:
                sleep(3)
                break
            else:
                sleep(3)
                gotimes += 1
            if gotimes == 4:
                break

    def test_down(self):
        self.d.app_stop(self.packageName)

    def write_log(self, file_path, str):
        '''
        报告录入工具
        :param str: 字符串
        :return: None
        '''
        if file_path is not None:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            with open(file_path, "a") as file:
                file.write(t + " " + str + "\n")
                file.close()

    def resize_image(self, file, width, height, type):
        img = Image.open(file)
        out = img.resize((width, height), Image.Resampling.LANCZOS)  # resize image with high-quality
        out.save(file, type)

    def start_netcfg(self, test_num, ssid, pwd):

        dingTalk = DingMessage()

        # 超过5次失败重启
        if self.fail_time > 5:
            self.write_serial = write_serial(self.com)
            self.write_serial.setCommand("reboot")
            self.write_serial.start()

        sleep(15)

        self.write_serial = write_serial(self.com)
        self.write_serial.setCommand("netcfg")
        self.write_serial.start()

        try:
            sleep(2)
            self.d(resourceId="com.wyze.gemini:id/iv_add").click(timeout=5)

            sleep(2)
            self.d(resourceId="com.wyze.gemini:id/tv_add_device").click(timeout=5)

            sleep(2)
            self.d(text="Cameras").click(timeout=5)
            # self.d.swipe(0, 2316, 0, 0)
            self.d.drag(50, 1100, 50, 100)

            sleep(2)
            self.d(text="Wyze Cam OG").click(timeout=5)

            sleep(2)
            self.d(resourceId="com.wyze.gemini:id/gm_btn_setup_next").click(timeout=5)

            sleep(1)
            self.d(resourceId="com.wyze.gemini:id/gm_cb_setup").click(timeout=5)

            sleep(2)
            self.d(resourceId="com.wyze.gemini:id/gm_btn_setup_next").click(timeout=5)

            if self.d(text='DEB9').exists:
                self.d(text='DEB9').click(timeout=5)

            # self.d(scrollable=True).scroll.toEnd()
            sleep(15)

            self.d.drag(50, 2310, 50, 10)
            self.d.drag(50, 2310, 50, 10)

            sleep(2)
            self.d(text="Other...").click(timeout=5)

            sleep(1)
            self.d(resourceId="com.wyze.gemini:id/wet_wpk_input_wifi_name").send_keys(ssid)

            sleep(1)
            self.d(resourceId="com.wyze.gemini:id/wet_wpk_input_wifi_password").send_keys(pwd)
            self.d(text="Connect").click(timeout=5)

            start_time = time.time()
            while int(time.time()) - int(start_time) < 20:
                if self.d(text="Name Your Cam").exists():
                    end_time = time.time()
                    total_time = end_time - start_time

                    self.write_log(self.result_path, str="第" + str(test_num) + "次测试，配网成功，耗时#" + str(total_time))
                    dingTalk.test_pass(take_time=str(total_time), test_num=test_num)

                    time.sleep(3)
                    return True

            dt = datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
            image = "./fail_pic/" + dt + ".png"
            self.d.screenshot(image)
            ResizeImage().resize_image(image, 216, 492, 'png')

            self.write_log(self.result_path, str="第" + str(test_num) + "次测试，配网失败")
            dingTalk.test_fail(test_num=test_num)
            return False

        except Exception as e:
            dt = datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
            image = "./fail_pic/" + dt + ".png"
            self.d.screenshot(image)
            ResizeImage().resize_image(image, 216, 492, 'png')

            print(e)
            dingTalk.test_error(test_num=test_num, error_info=str(e))
            return False


class read_serial(threading.Thread):

    def __init__(self, com):
        threading.Thread.__init__(self)
        self.com = com
        self.isRun = True

    def set_log_path(self, log_path):
        self.log_path = log_path

    def run(self):
        """
        读取串口
        :return:
        """
        while self.isRun:
            data = self.com.readline()
            self.write_txt(str(data), log_path=self.log_path)

    def stop(self):
        self.isRun = False

    def write_txt(self, str, log_path):
        """
        写入日志文件
        :param str:
        :return:
        """
        if not os.path.exists(os.path.dirname(log_path)):
            os.makedirs(os.path.dirname(log_path))

        log_dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')
        with open(log_path, "a") as f:
            f.write(log_dt + ' ' + str + '\n')
            f.close()


class write_serial(threading.Thread):

    def __init__(self, com):
        threading.Thread.__init__(self)
        self.command = None
        self.com = com

    def run(self):
        self.com.write(self.command.encode("utf-8"))
        self.com.write("\r\n".encode("utf-8"))

    def setCommand(self, command):
        self.command = command


class DingMessage:
    def __init__(self):
        self.URL = "https://oapi.dingtalk.com/robot/send" \
                   "?access_token=a15942794ce9e7dd3ad59654322e0407969014433195e4935edff1d1cb5b79ad"  # Webhook地址

        self.headers = {'Content-Type': 'application/json'}

    def test_fail(self, test_num):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "配网压力测试异常提示",
                "text": "#### **<font color=#FF0000>第" + str(test_num) + "次测试异常，配网失败" +
                        "**</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)

    def test_error(self, test_num, error_info):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "配网压力测试异常提示",
                "text": "#### **<font color=#FF0000>第" + str(test_num) + "次测试，脚本异常，错误信息：" + error_info +
                        "**</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)

    def test_pass(self, test_num, take_time):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "配网压力测试通过提示",
                "text": "#### **<font color=#7CFCOO>第" + str(test_num)
                        + "次测试通过**</font>\n\n""> **配网消耗时长:** <font color=#000000>"
                        + str(take_time) + "秒</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)


if __name__ == '__main__':
    test_time = int(input("请输入测试次数："))
    com_name = input("请问是串口几，如COM1，请输入COM1：")
    ssid = input("输入WIFI名：")
    pwd = input("输入WIFI密码:")
    # test_time = 1
    # com_name = "COM72"
    # ssid = "AX3000"
    # pwd = "29088360"

    com = serial.Serial(com_name, 115200)
    ng = netcfg(devices_name="R5CN806VZ4J", packageName='com.wyze.gemini', com=com)

    count = 1
    while count < test_time + 1:
        ng.set_up()
        if not ng.start_netcfg(test_num=count, ssid=ssid, pwd=pwd):
            count = count
            ng.fail_time += 1
        else:
            count += 1
            ng.fail_time = 0

    ng.read_serial.stop()
